package cn.itcast.pattern;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;

import static cn.itcast.pattern.Downloader.*;

@Slf4j(topic = "c.TestGuardedObject")
public class TestGuardedObject {
    public static void main(String[] args) {
        GuardedObject guardedObject = new GuardedObject();
        //等待结果线程
        new Thread(() -> {
            log.debug("waiting...");
            Object response = guardedObject.get();
            log.debug("get response: [{}] lines", ((List<String>) response).size());
        }, "getResult-Thread").start();

        //生产结果线程
        new Thread(() -> {
            try {
                guardedObject.complete(download());
                log.debug("download complete");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, "produceResult-Thread").start();
    }
}

class GuardedObject {

    //结果
    private Object response;

    //获取结果
    public Object get() {
        synchronized (this) {
            while (response == null) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            return response;
        }
    }

    //设置结果，唤醒等待线程
    public void complete(Object response) {
        synchronized (this) {
            this.response = response;
            this.notifyAll();
        }
    }
}